import axios from 'axios'
import { ElMessage } from 'element-plus'
import { userStores } from '@/stores/user'
import router from '@/router'
import 'element-plus/theme-chalk/el-message.css'

//创建axios实例

const http = axios.create({
  baseURL: 'http://pcapi-xiaotuxian-front-devtest.itheima.net',
  timeout: 50000
})

// axios请求拦截器
http.interceptors.request.use(
  (config) => {
    //创建userStores 实例
    const getUserStore = userStores()
    //从pinia中获取token数据
    const token = getUserStore.userInfo.token
    //安装后端的要求拼接token字段
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (e) => Promise.reject(e)
)

// axios响应式拦截器
http.interceptors.response.use(
  (res) => res.data,
  (e) => {
    //捕获401token失效状态  清除用户信息  跳转到登录页
    const getUserStore = userStores()
    if (e.response.status === 401) {
      //清除pinia中的用户信息

      //创建userStores 实例

      getUserStore.clearUser()

      //跳转到登录页
      router.push('/login')
    }
    //捕获登录错误提示
    ElMessage({
      type: 'warning',
      // e.response.data.msg
      message: '请您先登录'
    })
    return Promise.reject(e)
  }
)

export default http
